<template>
  <div class="container">
    <!-- 面包屑start -->
    <el-breadcrumb separator="/" class="breadCrumb_Box">
      <el-breadcrumb-item><a @click="goUrl('/mergeApplication', 'mergeApplication')">已合并应用</a></el-breadcrumb-item>
      <el-breadcrumb-item>{{ c_breadCrumb_name }}</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑end -->
    <div class="content">
      <div class="flex">
        <!-- <div class="app_icon" @click="triggerClick()">
          <img :src=icon alt="">
        </div>
        <div class="edit_icon">
          <span @click="triggerClick()">请修改图标</span>
          <input type="file" ref="file" style="display: none;" id="fileinput" @change="checkFileSure()">
        </div> -->
        <el-upload class="avatar-uploader" action="http://upload.ilucode.com/index/upfile/uploadfile/settingIconData"
          :auto-upload="false" :show-file-list="false" :on-change="handleAvatarChange">
          <img v-if="icon" :src="icon" class="avatar" />
          <img v-else src="../../../static/默认.png" class="avatar" />
        </el-upload>
        <div class="edit_icon">
          <span>请修改图标</span>
        </div>
      </div>
      <div class="from">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="110px" class="demo-ruleForm"
          style="margin-top: 40px;margin-left: 20px;margin-right: 20px;">
          <el-row>
            <el-col :xs="24" :sm="18" :md="18" :lg="18" :xl="18">
              <el-form-item label="应用名称：" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请您为新合并应用起一个名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="18" :md="18" :lg="18" :xl="18">
              <el-form-item label="短地址:" prop="shorturl">
                <el-input v-model="ruleForm.shorturl" placeholder="请输入短地址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
              <el-form-item label="下载按钮列表：">
                <el-button type="button" class="add" @click="addItem()">新增下载按钮</el-button>
              </el-form-item>
              <div class="box_list">
                <div class="list" v-for="(item, index) in list" :key="index">
                  <div class="check">
                    <el-checkbox v-model="item.checked" :key="index" @change="isCheck(item)"></el-checkbox>
                  </div>
                  <div class="form_control">
                    <div class="text">按钮名称：</div>
                    <div>
                      <input type="text" class="input" placeholder="输入名称" v-model="item.title" required="required"
                        :id="'name'+index" />
                    </div>
                  </div>
                  <div class="form_control">
                    <div class="text1">输入对应网址：</div>
                    <div class="flex flex-row">
                      <div>
                        <input type="text" class="input1" placeholder="输入对应网址" v-model="item.url" required="required"
                          :id="'link'+index" />
                      </div>
                      <div class="delete">
                        <el-button type="danger" icon="el-icon-delete" circle @click="der(index)"
                          :disabled="index===0||index===1||item.hasChecked===true?true:false"></el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row> -->
          <el-form-item class="button">
            <el-button type="primary" @click="submitList('ruleForm')"><span v-if="!appID">确认合并</span><span
                v-if="appID">保存修改</span></el-button>
            <el-button @click="goUrl('/mergeApplication', 'mergeApplication')">取消，返回上一层</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
      //这里存放数据
      return {
        c_breadCrumb_name: "外部导入链接合并",
        update: {}, //接收编辑数据
        ruleForm: {
          name: "",
          shorturl: ""
        },
        rules: {
          name: [{
            required: true,
            message: "请输入应用名称",
            trigger: "blur"
          }],
          shorturl: [{
            required: true,
            message: "请输入短地址",
            trigger: "blur"
          }]
        },
        list: [
          // {
          //   checked: true,
          //   title: "",
          //   url: ""
          // }
        ],
        icon: "", //上传的图标路径
        alyicom: "", //阿里云上传图标路径
        signature: {},
        hasChecked: false, //true禁用 false不禁用
      };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
      handleAvatarChange(file) {
        console.log(file);
        if (this.beforeAvatarUpload(file)) {
          this.icon = URL.createObjectURL(file.raw);
          if ("this.icon") {
            this.postImage(file.raw)
          }
        }
      },
      // 验证图片格式和大小
      beforeAvatarUpload(file) {
        console.log(file);
        const isJPG = file.raw.type === "image/jpeg";
        const isPNG = file.raw.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 1;
        if (!isJPG && !isPNG) {
          this.$message.error("上传头像图片只能是 JPG  PNG 格式!");
          return false;
        }
        // 如果该文件大于1M 则返回
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 1MB!");
          return false
        }
        console.log(isJPG);
        console.log(isPNG);
        console.log(isLt2M);
        return isJPG || (isPNG && isLt2M);
      },
      async getStsToken() {
        //验证返回 signature 失效时间
        let now = new Date().getTime() / 1000;
        // console.log(this.type,this.module);
        var params = new FormData();
        params.append("type", "1");
        params.append("module", "realname");
        console.log(this.signature);
        const expire = (this.signature.data && this.signature.data.expire) || 0;
        // 当前时间 + 3s 缓存 小于 过期时间 则 不用重新获取
        if (now + 3 < expire) return this.signature;
        else this.signature = await this.$post(this.API.getpolicy, params);
        console.log(this.signature);
        return this.signature;
      },
      // 该函数被handleAvatarSuccess调用
      postImage(file) {
        this.getStsToken().then(data => {
          // console.log(data);
          if (data) {
            // const { data } = data;
            let name = data.file_name;
            let obj = {
              host: data["host"],
              policy: data["policy"],
              OSSAccessKeyId: data["accessid"],
              signature: data["signature"],
              expire: parseInt(data["expire"]),
              callbackbody: data["callback"],
              // key: `${data["dir"]}`,
              key: `${data["dir"]}${name}`,
              // key: data.dir+name,
              success_action_status: "200",
              name
            };
            console.log(obj);
            const that = this;
            async function post() {
              try {
                var params = new FormData();
                params = new FormData();
                Object.keys(obj).forEach(k => params.append(k, obj[k]));
                params.append("file", file);
                // console.log(params);
                let upUrl = String(obj.host + "/" + obj.key).trim();
                that.$post(`${data["host"]}`, params).then(res => {
                  that.alyicom = upUrl;
                  console.log(that.alyicom);
                  console.log("上传成功");
                  console.log(res);
                });
              } catch (e) {
                console.log(e);
              }
            }
            post();
          } else {
            this.msgError("ERROR");
          }
        });
      },
      //新增
      addItem() {
        this.list.push({
          checked: false,
          title: "",
          url: ""
        });
      },
      //删除
      der(index) {
        this.list.splice(index, 1);
      },
      goUrl(path, name) {
        this.$router.push({
          path: path,
          name: name
        });
      },
      isCheck(item) {
        if (item.checked === true) {
          item.hasChecked = true;
        } else {
          item.hasChecked = false;
        }
      },
      //提交
      submitList(formName) {
        let hasEmpty = false;
        for (let i = 0; i < this.list.length; i++) {
          let item = this.list[i];
          let checked = item.checked;
          let title = item.title;
          let url = item.url;
          if (title.length == 0 || url.length == 0) {
            hasEmpty = true;
            break;
          }
        }
        if (hasEmpty) {
          this.$message.error('请完善信息！')
          return;
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var params = new FormData();
            params.append("icon", this.alyicom);
            params.append("appName", this.ruleForm.name);
            params.append("shorturl", this.ruleForm.shorturl);
            params.append("lists", JSON.stringify(this.list));
            if (this.appID > 0) {
              params.append("appID", this.appID);
              this.$post(this.API.customLink_addOrEdit, params).then(res => {
                console.log(res, "提交合并");
                if (res.code === 1) {
                  this.$message.success("修改成功!");
                  this.$router.push({
                    path: "/mergeApplication",
                    name: "mergeApplication"
                  });
                } else {
                  this.$message.error("修改失败!");
                }
              });
            } else {
              this.$post(this.API.customLink_addOrEdit, params).then(res => {
                console.log(res.code, "提交合并");
                if (res.code === 1) {
                  this.$message.success("合并成功!");
                  this.$router.push({
                    path: "/mergeApplication",
                    name: "mergeApplication"
                  });
                } else {
                  return
                }
              });

            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.appID = this.$route.query.appID;
      console.log(this.appID);
      if (this.$route.query.item === undefined) {
        this.update = null;
      } else {
        this.update = JSON.parse(this.$route.query.item);
        console.log(this.update, "item");
        this.alyicom = this.update.zxlogo_source
        this.icon = this.update.zxlogo;
        this.ruleForm.name = this.update.nickname;
        this.ruleForm.shorturl = this.update.shorturl;
        if (this.update.uptxt === null) {
          this.list = [];
        } else {
          this.list = this.update.uptxt;
        }
      }
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {}
  };

</script>
<style scoped>
  div>>>.el-button.is-circle {
    border-radius: 50%;
    padding: 6px;
    margin-left: 5px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 140px;
    height: 140px;
    border-radius: 8px;
    border: 1px solid #e3e3e3;
    margin-top: 100px;
    line-height: 140px;
    text-align: center;
  }

  .avatar {
    width: 140px;
    height: 140px;
    display: block;
    border-radius: 8px;
    border: 1px solid #e3e3e3;
    margin-top: 100px;
  }

  div>>>input[type="file"] {
    display: none;
  }

  /* 面包屑  */
  .breadCrumb_Box {
    margin-top: 30px;
  }

  .content {
    background: #ffffff;
    box-shadow: 0px 4px 10px 2px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    margin-top: 20px;
    margin-bottom: 30px;
  }

  .flex {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .app_icon img {
    width: 140px;
    height: 140px;
    border-radius: 8px;
    border: 1px solid #e3e3e3;
    margin-top: 100px;
  }

  .edit_icon {
    height: 18px;
    font-size: 18px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #1890ff;
    line-height: 18px;
    margin-top: 20px;
  }

  .from {
    margin-left: 200px;
  }

  div>>>.add {
    padding: 10px 20px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #1890ff;
    border: 1px solid #1890ff;
  }

  .box_list {
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #acd7ff;
    margin-top: -20px;
  }

  .list {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 10px 0px;
  }

  .text {
    width: 80px;
    height: 24px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #000000;
    line-height: 24px;
    text-align: right;
  }

  .text1 {
    width: 100px;
    height: 24px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #000000;
    line-height: 24px;
    text-align: right;
    margin-left: 30px;
  }

  .contorl {
    display: flex;
    flex-direction: row;
  }

  .label {
    height: 14px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #161616;
    line-height: 14px;
    text-align: right;
  }

  .input {
    width: 100%;
    min-width: 180px;
    height: 36px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 0px 10px;
  }

  input:focus {
    outline: none;
    border: 1px solid #e4e7ed;
  }

  .input1 {
    width: 100%;
    min-width: 220px;
    height: 36px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 0px 10px;
  }

  .check {
    margin-top: 6px;
    margin-left: 14px;
  }

  .form_control {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .button {
    margin-top: 80px;
    padding-bottom: 80px;
    margin-left: 130px;
  }

  input::-webkit-input-placeholder {
    color: #c4c8d0;
  }

  input::-moz-placeholder {
    /* Mozilla Firefox 19+ */
    color: #c4c8d0;
  }

  input:-moz-placeholder {
    /* Mozilla Firefox 4 to 18 */
    color: #c4c8d0;
  }

  input:-ms-input-placeholder {
    /* Internet Explorer 10-11 */
    color: #c4c8d0;
  }

  /* 媒体查询 */

  @media (max-width: 992px) {
    .form_control {
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: flex-start;
    }

    .text {
      text-align: left;
    }

    .text1 {
      margin-left: 0;
    }

    .list {
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: flex-start;
      margin-left: 40px;
    }

    .from {
      margin-left: 0px;
    }

    .check {
      margin-top: 0px;
      margin-left: 0px;
    }

    .button {
      margin-top: 80px;
      padding-bottom: 80px;
      margin-left: -40px;
    }
  }

  @media (max-width: 768px) {}

  @media (max-width: 576px) {}

</style>
